"""
LLM Inference Script with Streaming Output

Usage:
python demo4modelscope_stream.py [--model-path MODEL_PATH] [--prompt PROMPT]

Options:
  --model-path MODEL_PATH   Path to the model directory (default: /data/models/llm/models/QwQ-32B)
  --prompt PROMPT           Input prompt text (default: "How many r's are in the word \"strawberry\"")

Example:
python demo4modelscope_stream.py --model-path ./QwQ-32B --prompt "Explain quantum computing in simple terms"
"""

import argparse
from modelscope import AutoModelForCausalLM, AutoTokenizer
from transformers import TextStreamer
import torch

# 解析命令行参数
parser = argparse.ArgumentParser(description='Run QwQ model inference with streaming output')
parser.add_argument('--model-path', type=str, default="/data/models/llm/models/QwQ-32B",
                    help='Path to the model directory')
parser.add_argument('--prompt', type=str, default='How many r\'s are in the word "strawberry"',
                    help='Input prompt text')
args = parser.parse_args()

# 初始化模型和tokenizer
model = AutoModelForCausalLM.from_pretrained(
    args.model_path,
    torch_dtype=torch.float16,
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(args.model_path)

# 创建流式输出器
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)

# 构建对话模板
messages = [{"role": "user", "content": args.prompt}]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)

# 生成配置
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

# 执行生成并流式输出
print("\nGenerated Response:")
generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=32768,
    streamer=streamer,
)

# 最终完整结果解码
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]

# 打印最终整理结果（可选）
print("\n\nFinal Answer:")
print(response)